package servlets;

import java.io.IOException;
import java.util.List;
import java.util.Vector;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import services.FacadeVistaWeb;
import services.ServiceLocator;

import entities.VO.CondicionCompraVO;
import entities.VO.ProveedorVO;

/**
 * Servlet implementation class AltaProveedorServlet
 */
public class AltaProveedorServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
   
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		Integer idProveedor = null;
		if (request.getParameter("id")!=null && !"".equals(request.getParameter("id"))){
			idProveedor = Integer.parseInt(request.getParameter("id")); 
		}
		Integer condicionCompraid= null;
		if (request.getParameter("condicionCompraid")!=null && !"".equals(request.getParameter("condicionCompraid"))){
			condicionCompraid = Integer.parseInt(request.getParameter("condicionCompraid")); 
		}
		String razonSocial = request.getParameter("razonSocial");
		Boolean contado = null;
		Integer plazoDePago = null;
		Float interes = null;
		Float descuento = null;
		
		if ("0".equals(request.getParameter("condCompra"))){
			contado = true;
			descuento = Float.parseFloat(request.getParameter("descuento").replace(",", "."))/100;
		}else if ("1".equals(request.getParameter("condCompra"))){
			contado = false;
			plazoDePago = Integer.parseInt(request.getParameter("cantDias"));
			interes = Float.parseFloat(request.getParameter("interes").replace(",", "."))/100;
		}
		
		List<CondicionCompraVO> condicionesCompra = new Vector<CondicionCompraVO>();
		CondicionCompraVO condicionCompraVO = new CondicionCompraVO(null,contado, plazoDePago, interes, descuento);
		if (condicionCompraid != null){
			condicionCompraVO.setId(condicionCompraid);
		}
		condicionesCompra.add(condicionCompraVO);
		ProveedorVO proveedorVO = new ProveedorVO(null, razonSocial, condicionesCompra);
		
		ServiceLocator serviceLocator = new ServiceLocator(); 
		FacadeVistaWeb facade = serviceLocator.getFacade();
		if (idProveedor == null){
			facade.altaProveedor(proveedorVO);
		}else{
			proveedorVO.setIdProveedor(idProveedor);
			facade.actualizarProveedor(proveedorVO);
		}
		
		request.getRequestDispatcher("listaproveedor").forward(request, response);
	}

}
